package com.edu.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.edu.common.constant.CONSTANT;

public class SecurityInterceptor implements HandlerInterceptor{
	
	private static Logger logger = Logger.getLogger(SecurityInterceptor.class);
	
	private String indexUrl;

	@Override
	public boolean preHandle(HttpServletRequest pArg0, HttpServletResponse pArg1, Object pArg2) throws Exception {
		logger.info("---开始权限验证---");
		//token+posttime+customFields
		String token = pArg0.getParameter("token");//接口请求加密串
		String posttime = pArg0.getParameter("posttime");//接口请求时间
		if(StringUtils.isBlank(token) || StringUtils.isBlank(posttime)){
			logger.info("权限验证失败；权限参数为空！");
			pArg1.getWriter().print("权限验证失败；权限参数为空！");
			return false;
		}else{
			if(!token.toLowerCase().equals(CONSTANT.token)){
				logger.info("权限验证失败；权限参数异常！");
				pArg1.getWriter().print("权限验证失败；权限参数异常！");
				return false;
			}
			long postTime = Long.parseLong(posttime);
			long currentTime = System.currentTimeMillis();
			int interval = (int) ((currentTime-postTime)/1000/60);
			if(interval>1){
				logger.info("权限验证失败；权限参数超时！");
				pArg1.getWriter().print("权限验证失败；权限参数超时！");
				return false;
			}
		}
		return true;
	}
	
	@Override
	public void afterCompletion(HttpServletRequest pArg0, HttpServletResponse pArg1, Object pArg2, Exception pArg3) throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest pArg0, HttpServletResponse pArg1, Object pArg2, ModelAndView pArg3) throws Exception {
		
	}

	public String getIndexUrl() {
		return indexUrl;
	}
	public void setIndexUrl(String pIndexUrl) {
		indexUrl = pIndexUrl;
	}

}
